<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/21
 * Time: 22:49
 */

namespace api\controllers;


use api\ext\Cookie;
use api\models\User;
use corephp\App;
use corephp\web\Request;

class UserController extends Base
{
    private $algo = PASSWORD_DEFAULT;
    public function resetPassword()
    {
        $oldPassword = Request::post('oldPassword');
        $password = Request::post('password');
        $password2 = Request::post('password2');
        $model = new User();
        $user = $model->where(['id'=>1])->get();

        if($password != $password2){
            return json_encode([
                'status'=>-1,
                'msg'=>'两次输入的密码不一致'
            ]);
        }
        if(password_verify($oldPassword,$user['password'])){
            $model->data([
                'password'=>password_hash($password,$this->algo)
            ])->update();

            return json_encode([
                'status'=>1,
                'msg'=>'密码修改成功'
            ]);
        }else{
            return json_encode([
                'status'=>-1,
                'msg'=>'旧密码错误'
            ]);
        }
    }

    public function checkAuth()
    {
        $cookie = new Cookie();
        $model = new User();
        $user = $model->where(['id'=>1])->get();
        $route = App::route()->parse();
        if(in_array($route['action'],['search','foods','detail','articles','hotArticles'])){
            return json_encode(['status'=>1]);
        }
        if(password_verify($user['username'].$user['password'],$cookie->get('auth') )){
            return json_encode(['status'=>1]);
        }else{
            return json_encode(['status'=>0]);
        }
    }
    public function login()
    {
        $username = Request::post('username');
        $password = Request::post('password');
        $model = new User();
        $user = $model->where(['username'=>$username])->get();
        if(!$user){
            return json_encode([
                'status'=>-1,
                'msg'=>'用户名密码错误'
            ]);
        }

        if(password_verify($password,$user['password'])){
            $cookie = new Cookie();
            $cookie->set('auth',password_hash($user['username'].$user['password'],$this->algo));

            return json_encode([
                'status'=>1,
                'msg'=>'登录成功'
            ]);
        }else{
            return json_encode([
                'status'=>-1,
                'msg'=>'用户名密码错误'
            ]);
        }
    }
}